#include "NetworkManager.h"

#include <memory>

NetworkManager::NetworkManager() :
    socket_(nullptr)
{
}

NetworkManager::~NetworkManager()
{
    disconnect();
}

NetworkManager *NetworkManager::getInstance()
{
    static NetworkManager s_network_manager;
    return &s_network_manager;
}

bool NetworkManager::init()
{
    return true;
}

bool NetworkManager::connect(const std::string &url)
{
    if (socket_ != nullptr) {
        return false;
    }

    std::unique_ptr<cocos2d::network::WebSocket> socket(
        new cocos2d::network::WebSocket());
    if (socket->init(*this, url) == false) {
        return false;
    }
    socket_ = socket.release();
}

void NetworkManager::disconnect()
{
    if (socket_ != nullptr) {
        socket_->close();
        CC_SAFE_DELETE(socket_);
    }
}

void NetworkManager::onOpen(cocos2d::network::WebSocket* ws)
{
    CCLOG("web socket open");
}

void NetworkManager::onMessage(cocos2d::network::WebSocket* ws,
    const cocos2d::network::WebSocket::Data& data)
{
    CCLOG("web socket recv message");
}

void NetworkManager::onClose(cocos2d::network::WebSocket* ws)
{
    CCLOG("web socket close");
}

void NetworkManager::onError(cocos2d::network::WebSocket* ws,
    const cocos2d::network::WebSocket::ErrorCode& error)
{
    CCLOG("web socket error(%d)", error);
}

